//index.js
//获取应用实例
const app = getApp()
const Pager = require('components/aotoo/core')
import createCalendar, {getYmd, lunar, diffDay} from 'components/modules/calendar/index'
import {mkDateInfo, today, daystamp, setCaseStatistics, setPanReciprocal, emptyRecentReciprocal, announcePop} from './common/dateinfo/index'
import {casePrefix, getMarkDates, diffCycleDays} from './funcs/index'
// import {readmeInfo} from './common/readme'
// import {shareInpageOnload, shareModal, openShareModal, onShareAppMessage} from './common/dateinfo/share/index'

import {
  holidays,
  works,
  nextHolidays,
  followHolidays,
  nextWorks,
} from './common/holidays'

const markDates = getMarkDates()||[]

const createCalendarConfig = () => {
  return createCalendar({
    mode: 3,
    lunar: true,
    festival: true,
    created(){
      this.tapDay = today; // 用户点击的日期
      this.today = today
      this.activePage.tapDay = this.tapDay
      this.activePage.today = today;
    },
    ready(){
      wx.calendarInst = this
    },
    bindchange: function(param){
      // swiper切换时的响应方法
      const year = param.year
      const month = param.month
      console.log(this, '========== this')
      this.changeHeaderTitle({
        title: `${year}年${month}月`,
        itemClass: 'calendar-title'
      })
    },
    tap(e, param, inst){
      const td = param.lunarDate
      let timmer = null
      clearTimeout(timmer)
      const pitsListInst = this.activePage.getElementsById('pits-list')
      if (pitsListInst) {
        pitsListHooks.emit('reset-data', {
          callback: function () {
            timmer = setTimeout(() => {
              const temp = pitsListInst.getData().data.filter(data=>{
                const ymd = getYmd(data.date)
                const month_day = ymd.month + '-' + ymd.day
                const param_month_day = param.month + '-' + param.day
                return param_month_day === month_day
              })
              if (temp.length) {
                allowReset = true
                pitsListInst.update(temp)
              } else {
                if (allowReset) {
                  pitsListHooks.emit('reset-data', {callback(){
                    allowReset = false
                  }})
                }
              }
            }, 200);
          }
        })
      }

      if (this.tapDay.timestr === param.timestr) return
      const lunarDate = param.lunarDate
      const treeid = param['data-treeid']
      const tapDay = {...getYmd(param.timestr), lunarDate, "data-treeid": treeid} 
      this.tapDay = tapDay
      this.activePage.tapDay = tapDay

      this.changeHeaderTitle({
        title: [
          `${param.year}年${param.month}月${param.day}日`,
          `${td.gzYear}年「${td.Animal}」| ${td.gzMonth}月${td.gzDay}日 | 农历${td.IMonthCn}${td.IDayCn} | ${td.astro}`
        ],
        titleStyle: 'font-size: 18px; display: flex; flex-direction: column; ustify-content: flex-start; align-items: flex-start;'
      })

//         infoBox.update({
//           title: param.day,
//           '@md': {
//             content: `#### ${param.year}「${param.month}月」  
// ### ${td.ncWeek}  
// ### ${td.astro}  
// #### ${td.gzYear}年「${td.Animal}」   
// #### ${td.gzMonth}月「${td.IMonthCn}」`
//           }
//         })
    },

    // 显示隐藏信息列表
    longpress(e, param, inst){
      const curDate = param.month + '-' + param.day
      let res = (caseHooks.getList() || []).sort((a,b)=>b.createtime-a.createtime)
      const temp = []
      res.forEach(item=>{
        if (item.value.hideDate === curDate) {
          temp.push(item)
        }
      })

      if (temp.length) {
        const contents = temp.map(item=>(item.value))
        contents.unshift({
          title: '返回默认列表', 
          itemClass: 'default-list-button',
          tap(){
            pitsListHooks.emit('reset-data') 
          }
        })
        pitsListHooks.emit('update-data', {data: contents})
      }
    },

    date: function (param) {
      const theHolidays = [...holidays, ...nextHolidays]
      const theWorks = [...works, ...nextWorks]

      if (theHolidays.includes(param.id)) {
        param.itemClass = (param.itemClass || '') + ' holiday'
      }
      
      if (theWorks.includes(param.id)) {
        param.itemClass = (param.itemClass || '') + ' workday'
      }

      markDates.forEach(date=>{
        if (param.solarDate.day === date.day) {
          if (date.className.indexOf('salary')>-1) {
            param.itemClass = (param.itemClass || '') + ` ${date.className}`
          } 
          else if (date.className.indexOf('menstruation')>-1){
            markDates['menstruation'] = []
            markDates['menstruationDays'] = []
            const interval = date.interval
            for (let ii=0; ii<parseInt(interval); ii++) {
              const tempDate = getYmd(param.id)
              tempDate.className = date.className
              if (ii > 0) {
                const offsetDate  = tempDate.offset(ii)
                offsetDate.className = date.className
                markDates['menstruation'].push(offsetDate)
                markDates['menstruationDays'].push(offsetDate.day)
              } else {
                markDates['menstruation'].push(tempDate)
                markDates['menstruationDays'].push(tempDate.day)
              }
            }
            // param.itemClass = (param.itemClass || '') + ` ${date.className}`
          }
          else {
            if (param.solarDate.month === date.month) {
              if (['reciprocal', 'memo'].includes(date.className)) {
                if (param.solarDate.year === date.year) {
                  param.itemClass = (param.itemClass || '') + ` ${date.className}`
                }
              } else {
                param.itemClass = (param.itemClass || '') + ` ${date.className}`
              }
            }
          }
        }
      })

      if (markDates['menstruation'] && markDates['menstruation'].length) {
        const menstruation = markDates['menstruation']
        const menstruationDays = markDates['menstruationDays']
        if (menstruationDays.includes(param.solarDate.day)) {
          menstruation.forEach(date=>{
            if (param.solarDate.day === date.day) {
              param.itemClass = (param.itemClass || '') + ` ${date.className}`
            }
          })
        }
      }


      return param
    },
  })
}

Pager({
  data: {
    calendarConfig: null,
  },
  onShow: function () {},
  onReady() {
    setTimeout(() => {
      // 日历、列表
      this.setData({
        calendarConfig: createCalendarConfig(),
      })

    }, 10);
  },
  onLoad: function () {},
})
